/*
 * Copyright 2007 Johan Andries
 *
 * This file is released under the LGPL v2.1.
 * 
 * This file may be redistributed under the terms of the Library GNU Public
 * License.
 */

package rubymatic;

import org.jruby.Ruby;
import org.jruby.RubyModule;
import org.jruby.RubyClass;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.javasupport.JavaUtil;

import java.io.Serializable;

import org.hibernate.mapping.PersistentClass;
import org.hibernate.tuple.Instantiator;
import org.hibernate.mapping.Component;


public class RubyInstantiator implements Instantiator {

	private String[] modulesAndClassNames;


	public RubyInstantiator(Component component) {
		modulesAndClassNames = component.getComponentClassName().split("\\.");
	}
	
	public RubyInstantiator(PersistentClass mappingInfo) {
		modulesAndClassNames = mappingInfo.getEntityName().split("\\.");
	}
	
	public Object instantiate(Serializable id) {
		Ruby runtime = ActiveHibernateUtil.getRubyInstance();
		RubyClass rubyClass = null;
		if(modulesAndClassNames.length==1) {
			rubyClass = runtime.getClass(modulesAndClassNames[0]);
		} else {
			RubyModule module = runtime.getModule(modulesAndClassNames[0]);
			for(int i=1; i<modulesAndClassNames.length-1; i++) {
				module = (RubyModule)module.getConstant(modulesAndClassNames[i]);
			}
			rubyClass = module.getClass(modulesAndClassNames[modulesAndClassNames.length-1]);
		}
		IRubyObject ro = rubyClass.newInstance(new IRubyObject[0], null);
				
		return ro;
	}

	public Object instantiate() {
		return this.instantiate(null);
	}

	public boolean isInstance(Object object) {
		return object instanceof IRubyObject;
	}

}
